package com.ck.reactor.ckreactor.exmple;

import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.time.Duration;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @Classname
 * @Description TODO
 * @Date 2021/2/4 15:07
 * @Created by lpc
 */
public class TestReactor {

    public static void main(String[] args) {
//        fluxCreate();
//        fluxGenerate();
//        rang();
//        defer();
//        fromCallable();
        delay();
        fromIterable();
    }

    /**
     * 创建flux
     */
    public static void  fluxCreate(){
        Flux.create((t)->{
            t.next("create");
            t.next("create1");
            t.complete();
        }).subscribe(System.out::println);
    }

    /**
     *
     */
    public static void fluxGenerate(){
        Flux.generate(t->{
            t.next("generate");
            //注意generate中next只能调用1次
            t.complete();
        }).subscribe(System.out::println);
    }

    /**
     * 创建一个Flux，它发出所提供的元素，然后完成。
     * 不需要如上fluxCreate()，fluxGenerate()  t.complete();
     */
    public static void fluxJust(){
        //单个元素
        Flux.just("just").subscribe(System.out::println);
        //多个元素
        Flux.just("just1","just2","just3").subscribe(System.out::println);
    }

    /**
     * 用Flux API装饰指定的Publisher,通过Publisher创建一个Flux
     */
    public static void fluxFrom(){
        //Flux->Flux
        Flux.from(Flux.just("just","just1","just2")).subscribe(System.out::println);
        //Mono->Mono
        Flux.from(Mono.just("just")).subscribe(System.out::println);
    }

    public static void fluxFromArray(){
        Flux.fromArray(new String[] {"arr1","arr2","arr3","arr4"}).subscribe(System.out::println);
    }

    public static void rang(){
        Flux.range(0,10)
                .timeout(Flux.never(),v->Flux.never())
                .subscribe(System.out::println);
    }

    public static void defer(){
        Mono.defer(()->{
            return Mono.error(new RuntimeException());
        }).subscribe();
    }


    public static void fromCallable(){
        Mono.fromCallable(()->"9999").subscribe(System.out::println);
    }


    public static void delay(){
        Mono.delay(Duration.ofSeconds(3)).doOnNext(System.out::println).block();

    }

    /**
     * 迭代器，存储集合试用
     */
    public static void fromIterable() {
        Set<String> v = new HashSet<>();
        v.add("1");
        v.add("2");
        v.add("3");
        Flux.fromIterable(() -> v.iterator()).subscribe(System.out::println);

    }












}
